<?php

namespace app\admin\controller;

use think\Config;
use think\Controller;


class Cate extends Base
{
    public function upload_api()
    {
// 创建一个关联数组
        $data = array(
            'name' => 'John Doe',
            'age' => 30,
            'city' => 'New York'
        );

// 将数据转换为JSON格式
        $jsonData = json_encode($data);

// 设置Content-Type头信息为application/json
        header('Content-Type: application/json');

// 输出JSON数据
        echo $jsonData;
        die();

        header('Content-Type:application/json');
//        $arr = [
//            "download_url" => "http://xxx.xxx.xxx.xxx/update/EasyClick/release.iec",
//            "version" => "1.1.0",
//            "dialog" => true,
//            "msg" => "更新公告",
//            "force" => false
//        ];
//        echo json_encode($arr);
//
//        die();


        $data = array('name' => 'John', 'age' => 30);
        header('Content-Type: application/json');
        echo json_encode($data);


        header('Content-Type: application/json');
        $result = [];


        if (request()->file('image')) {
            # code...


            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('image');


            // 移动到框架应用根目录/public/uploads/ 目录下
            // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            $info = $file->move(ROOT_PATH . 'public' . DS . 'static/uploads');
//            $info = $file->move(ROOT_PATH . 'vendor' . DS . '/PHPExcel66/Documentation/Examples/Reader/sampleData');
            //vendor\PHPExcel66\Documentation\Examples\Reader\sampleData
            //var_dump($info); die;
            if ($info) {
                // 成功上传后 获取上传信息
                // 输出 jpg

                //    echo $info->getExtension();
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg

                //   echo $info->getSaveName();
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                //echo $info->getFilename();
//                $datapic = '/' . date('Ymd') . '/' . $info->getFilename();
                //echo $datapic;'username'=>session('username'),

//                $url = '/gmt/vendor/PHPExcel66/Documentation/Examples/Reader/exampleReader01.php?name=' . $datapic . '&m=&username=' . session('username');
                Config::set('default_return_type', 'json');

                $result['code'] = 200;
                $result['msg'] = '上传成功 !' . $info->getSaveName();
                $result['filename'] = $info->getFilename();

            } else {
                // 上传失败获取错误信息
                $result['code'] = 400;
                $result['msg'] = '上传失败 !' . $file->getError();


            }
        } else {
            // 上传失败获取错误信息
            $result['code'] = 410;
            $result['msg'] = '没有选择文件';
        }

        // 返回上传结果
        return json($result);
//        return  json_encode($result) ;

    }

    public function lst()
    {
        //return session('username');
        if (session('username') == 'admin') {
            # code...
            $cateres = \think\Db::name('cate')->order('id desc')->paginate(10);
        } else {
            $cateres = \think\Db::name('cate')->where('username', '=', session('username'))->order('id desc')->paginate(10);
        }

        $this->assign('cateres', $cateres);
        return $this->fetch();
    }

    public function add()
    {
        if (request()->isPost()) {
            $data = [
                'catename' => input('catename'),
                //'keywords'=>input('keywords'),
                'desc' => input('desc'),
                // 'gmt'=>input('gmt'),
                // 'title1'=>input('title1'),
                // 'type'=>input('type') ? input('type') : 0,
                'username' => session('username'),
                'time' => time(),
            ];
            //var_dump(input('post.'));
            //echo input('title');
            //echo ;

            $validate = \think\Loader::validate('Cate');
            if ($validate->check($data)) {
                //$db= \think\Db::name('cate')->insert($data);
                $dx = \think\Db::name('cate')->insertGetId($data);

                $i = 1;
                $title = (count(input('post.')) - 2) / 8;
                // echo $title;
                while ($i <= $title) {
                    $data1['title'] = input('title' . $i);
                    $data1['type'] = input('type' . $i);
                    $data1['score'] = input('score' . $i);
                    $data1['answer1'] = input('answer1' . $i);
                    $data1['answer2'] = input('answer2' . $i);
                    $data1['answer3'] = input('answer3' . $i);
                    $data1['answer4'] = input('answer4' . $i);
                    $data1['answer5'] = input('answer5' . $i);
                    $data1['answer6'] = input('answer6' . $i);
                    $data1['cate'] = $dx;

                    // 接收对应的答案，进行合并
                    $correct['answer1'] = input('correct1' . $i)?'A':'';
                    $correct['answer2'] = input('correct2' . $i)?'B':'';
                    $correct['answer3'] = input('correct3' . $i)?'C':'';
                    $correct['answer4'] = input('correct4' . $i)?'D':'';
                    $correct['answer5'] = input('correct5' . $i)?'E':'';
                    $correct['answer6'] = input('correct6' . $i)?'F':'';


                    // 过滤掉空值
                    $filteredArray = array_filter($correct, function($value) {
                        return $value !== null && $value !== "";
                    });

                    // 将数组元素合并为一个字符串
                    $data1['correct'] = implode(", ", $filteredArray);




                    // echo $data1['title'.$i];
                    // echo $data1['answer1'.$i];
                    $i++;
                    $d1 = \think\Db::name('cate_contens')->insert($data1);
                }


                $data1d = [
                    // 'catename'=>input('catename'),
                    // 'keywords'=>input('keywords'),
                    // 'desc'=>input('desc'),
                    // 'gmt'=>input('gmt'),

                    'title' => input('title'),
                    'contens' => input('contens'),
                    'cate' => $dx,
                    // 'type'=>input('type') ? input('type') : 0,

                ];
                $data2d = [
                    // 'catename'=>input('catename'),
                    // 'keywords'=>input('keywords'),
                    // 'desc'=>input('desc'),
                    // 'gmt'=>input('gmt'),
                    'title' => input('title'),
                    'type' => input('type'),
                    'answer1' => input('answer1'),
                    'answer2' => input('answer2'),
                    'answer3' => input('answer3'),
                    'answer4' => input('answer4'),
                    'answer5' => input('answer5'),
                    'answer6' => input('answer6'),
                    'cate' => $dx,
                    // 'type'=>input('type') ? input('type') : 0,

                ];

                // $d2= \think\Db::name('cate_contens')->insert($data2);

                //var_dump($dx);
                if ($dx) {
                    return $this->success('添加模板成功！', 'lst');
                } else {
                    return $this->error('添加模板失败！');
                }
            } else {
                // var_dump("25555");
                return $this->error($validate->getError());
                //return 'youkong';
            }
            return;
        }
        return $this->fetch();
    }



    public function edit()
    {

        if (request()->isPost()) {
            $data = [
                'id' => input('id'),
                'catename' => input('catename'),
                //'keywords'=>input('keywords'),
                'title' => input('title'),
                'desc'=>input('desc'),
                'time' => time(),
                //'type'=>input('type'),
            ];

            $titleo = (count(input('post.')) - 1) / 8;
            //echo count(input('post.'));exit();
            for ($i = 1; $i <= $titleo; $i++) {
                # code...
                $data1['title'] = input('title' . $i);
                $data1['type'] = input('type' . $i);
                $data1['score'] = input('score' . $i);

                $data1['answer1'] = input('answer1' . $i);
                $data1['answer2'] = input('answer2' . $i);
                $data1['answer3'] = input('answer3' . $i);
                $data1['answer4'] = input('answer4' . $i);
                $data1['answer5'] = input('answer5' . $i);
                $data1['answer6'] = input('answer6' . $i);

                // 接收对应的答案，进行合并
                $correct['answer1'] = input('correct1' . $i)?'A':'';
                $correct['answer2'] = input('correct2' . $i)?'B':'';
                $correct['answer3'] = input('correct3' . $i)?'C':'';
                $correct['answer4'] = input('correct4' . $i)?'D':'';
                $correct['answer5'] = input('correct5' . $i)?'E':'';
                $correct['answer6'] = input('correct6' . $i)?'F':'';


                // 过滤掉空值
                $filteredArray = array_filter($correct, function($value) {
                    return $value !== null && $value !== "";
                });

                // 将数组元素合并为一个字符串
                $data1['correct'] = implode(", ", $filteredArray);







                $d1 = \think\Db::name('cate_contens')->where('id', input('id' . $i))->update($data1);

            }


            $validate = \think\Loader::validate('Cate');
            if ($validate->scene('edit')->check($data)) {
                if ($db = \think\Db::name('cate')->update($data)) {
                    return $this->success('修改问卷模板成功！', 'lst');
                } else {
                    return $this->error('修改问卷模板失败！');
                }
            } else {
                return $this->error($validate->getError());
            }


            return;
        }
        $id = input('id');
        $cates = db('cate')->where('id', $id)->find();
        $this->assign('cates', $cates);
        $cate_contens = db('cate_contens')->order('id asc')->where('cate', $id)->select();

        // 把合并的答案拆分出来，用于修改时显示所设置的答案


        foreach ($cate_contens as $key=>$value){

            // 默认初始值
            $cate_contens[$key]['correct1'] = 0;
            $cate_contens[$key]['correct2'] = 0;
            $cate_contens[$key]['correct3'] = 0;
            $cate_contens[$key]['correct4'] = 0;
            $cate_contens[$key]['correct5'] = 0;
            $cate_contens[$key]['correct6'] = 0;

            $check_correct = $value['correct'];
            // 检查字符串中是否包含字母"A"或"B"
            if (strpos($check_correct, 'A') !== false) {
                // 如果找到字母"A"，返回"A"
                $cate_contens[$key]['correct1'] = 1;
            }
            if (strpos($check_correct, 'B') !== false) {
                // 如果找到字母"B"，返回"B"
                $cate_contens[$key]['correct2'] = 1;
            }

            if (strpos($check_correct, 'C') !== false) {
                // 如果找到字母"B"，返回"B"
                $cate_contens[$key]['correct3'] = 1;
            }

            if (strpos($check_correct, 'D') !== false) {
                // 如果找到字母"B"，返回"B"
                $cate_contens[$key]['correct4'] = 1;
            }
            if (strpos($check_correct, 'E') !== false) {
                // 如果找到字母"B"，返回"B"
                $cate_contens[$key]['correct5'] = 1;
            }
            if (strpos($check_correct, 'F') !== false) {
                // 如果找到字母"B"，返回"B"
                $cate_contens[$key]['correct6'] = 1;
            }

        }




        $this->assign('cate_contens', $cate_contens);
        return $this->fetch();

    }

    public function del()
    {
        $id = input('id');
        if (db('cate')->delete($id)) {
            return $this->success('删除栏目成功！', 'lst');
        } else {
            return $this->error('删除栏目失败！');
        }
    }

    public function upload()
    {

        if (request()->file('image')) {
            # code...

// 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('image');


// 移动到框架应用根目录/public/uploads/ 目录下
            // $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            // $info = $file->move(ROOT_PATH . 'public' . DS . '/static/uploads');
            $info = $file->move(ROOT_PATH . 'vendor' . DS . '/PHPExcel66/Documentation/Examples/Reader/sampleData');
            //vendor\PHPExcel66\Documentation\Examples\Reader\sampleData
            //var_dump($info); die;
            if ($info) {
// 成功上传后 获取上传信息
// 输出 jpg

//    echo $info->getExtension();
// 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                // //
//   echo $info->getSaveName();
// 输出 42a79759f284b767dfcb2a0197904287.jpg
                //echo $info->getFilename();
                $datapic = '/' . date('Ymd') . '/' . $info->getFilename();
                //echo $datapic;'username'=>session('username'),

                $url = '/score/vendor/PHPExcel66/Documentation/Examples/Reader/exampleReader01.php?name=' . $datapic . '&m=&username=' . session('username');
                echo '<h2><a href="' . $url . '"> 上传成功，提交导入</a></h2>';
            } else {
// 上传失败获取错误信息
                echo $file->getError();

            }
        } else {
            return "没有选择文件";
        }

// 获取到一个数组，把数组信息写入到表中  循环遍历数组，循环存入数据

    }

    public function join()
    {
//  //使用方法：
// Vendor("PHPExcel.IOFactory");
// $objPHPExcel = \PHPExcel_IOFactory::load(ROOT_PATH . "./Data/data.xlsx");
// $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);

// exit();

        if (request()->isPost()) {
            $data = [
                'catename' => input('catename'),
                'keywords' => input('keywords'),
                'desc' => input('desc'),
                // 'gmt'=>input('gmt'),
                'title' => input('title'),
                // 'type'=>input('type') ? input('type') : 0,

            ];


            $validate = \think\Loader::validate('Cate');
            if ($validate->check($data)) {
                //$db= \think\Db::name('cate')->insert($data);
                $dx = \think\Db::name('cate')->insertGetId($data);
                $data1 = [
                    // 'catename'=>input('catename'),
                    // 'keywords'=>input('keywords'),
                    // 'desc'=>input('desc'),
                    // 'gmt'=>input('gmt'),

                    'title' => input('title'),
                    'contens' => input('contens'),
                    'cate' => $dx,
                    // 'type'=>input('type') ? input('type') : 0,

                ];
                $data2 = [
                    // 'catename'=>input('catename'),
                    // 'keywords'=>input('keywords'),
                    // 'desc'=>input('desc'),
                    // 'gmt'=>input('gmt'),
                    'title' => input('title2'),
                    'type' => input('type'),
                    'answer1' => input('answer1'),
                    'answer2' => input('answer2'),
                    'answer3' => input('answer3'),
                    'answer4' => input('answer4'),
                    'answer5' => input('answer5'),
                    'answer6' => input('answer6'),
                    'cate' => $dx,
                    // 'type'=>input('type') ? input('type') : 0,

                ];
                $d1 = \think\Db::name('cate_contens')->insert($data1);
                $d2 = \think\Db::name('cate_contens')->insert($data2);

                //var_dump($dx);
                if ($dx) {
                    return $this->success('添加模板成功！', 'lst');
                } else {
                    return $this->error('添加模板失败！');
                }
            } else {
                // var_dump("25555");
                return $this->error($validate->getError());
                //return 'youkong';
            }
            return;
        }
        return $this->fetch();
    }


    /**
     *
     * 导出Excel
     */
    public function expExcel()
    {//导出Excel
        $fileName = date('_YmdHis');

        $xlsData = "aa";
        $this->assign('list', $xlsData);
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $fileName . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印


    }

    public function out()
    {
        $fileName = session('username') . date('_YmdHis');
        header("Content-type:application/vnd.ms-excel;charset=utf-8");
        header("Content-Disposition:attachment;filename=$fileName.xls");


        $tab = "\t";
        $br = "\n";
        $head = "编号" . $tab . "问卷标题" . $tab . "问卷标题";
        // //输出内容如下： 
        echo $head . $br;
//        echo  "test321318312".$tab; 
//        echo  "string1";
//        echo  $br;

//         echo  "330181199006061234".$tab;  //直接输出会被Excel识别为数字类型
//         echo  "number";
//         echo  $br;

//         echo  "=\"330181199006061234\"".$tab;  //原样输出需要处理
//         echo  "string2";
//         echo "guomengtao";
//         echo  $br;

//return session('username');
        if (session('username') == 'admin') {
            # code...
            $cateres = \think\Db::name('cate')->order('id desc')->paginate(100);
        } else {
            $cateres = \think\Db::name('cate')->where('username', '=', session('username'))->order('id desc')->paginate(100);
        }
        //var_dump($cateres);
        // 获取数据集记录数
        $count = count($cateres);
        // 遍历数据集
        foreach ($cateres as $user) {
            echo $user['id'] . $tab;
            echo $user['catename'] . $tab;
            echo $user['desc'];
            echo $br;
        }
        // $this->assign('cateres',$cateres);
        // $this->assign('tab',$tab);
        // $this->assign('br',$br);
        // return $this->fetch();


    }


}
